<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Repositories\CategoryRepository;

class CategoryController extends ManageBaseController
{

    private $categoryRepo = NULL;

    public function __construct(CategoryRepository $categoryRepo)
    {
        parent::__construct();
        $this->categoryRepo = $categoryRepo;
    }

    public function index()
    {
        $filter = request()->all();
        $res = $this->categoryRepo->getList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function detail($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");
        $res = $this->categoryRepo->getOne($id);
        return retSuc($res);
    }

    public function update($id = null)
    {
        $data = request()->only(['id', 'shop_id', 'title', 'sort', "status"]);
        $last_id = $this->categoryRepo->saveOrUpdate($data, $id ?? 0);

        if (!$data['shop_id']) {
            return retFail("所属店铺必填");
        }

        if (!$last_id) {
            return retFail(empty($data['id']) ? "新增失败" : "更新失败");
        }

        $res = $this->categoryRepo->getOne(intval($last_id));
        return retSuc($res);
    }

    public function delete($id = null)
    {
        $ids = array_filter(array_unique(explode(",", $id)));
        if (empty($ids)) {
            return retFail("参数错误");
        }

        if (empty($id)) {
            return retFail("参数错误");
        }

        return $this->categoryRepo->batchDelete($id);
    }


    public function options()
    {
        $res = $this->categoryRepo->getOptions();
        return retSuc($res);
    }

}
